package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.zzyl.service.RoleService;

import java.util.Arrays;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageResponse<RoleVo> queryPage(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        String roleName = roleDto.getRoleName();
        PageHelper.startPage(pageNum, pageSize);
        Page page = roleMapper.queryPage(roleName);
        return PageResponse.of(page, RoleVo.class);

    }

    @Override
    public void add(RoleDto roleDto) {
        RoleVo roleVo = BeanUtil.toBean(roleDto, RoleVo.class);
        roleMapper.insert(roleVo);
    }

    @Override
    public List<String> findCheckedResources(Long roleId) {
        return roleMapper.findCheckedResources(roleId);

    }

    @Override
    public void update(RoleDto roleDto) {
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        // 判断是否是菜单权限修改
        if(ObjectUtil.isNotEmpty(checkedResourceNos)){
            roleMapper.deleteResourceByRoleId(roleDto.getId());

            Arrays.stream(checkedResourceNos).forEach(resourceNo -> {
                RoleResource roleResource = new RoleResource();
                roleResource.setRoleId(roleDto.getId());
                roleResource.setResourceNo(resourceNo);
                roleMapper.addResourceByRoleId(roleResource);
            });
        }
        else {
            Role role = BeanUtil.copyProperties(roleDto, Role.class);
            Role roleSql = roleMapper.selectById(role.getId());
            if("1".equals(role.getDataState())&&"0".equals(roleSql.getDataState())){
                if(ObjectUtil.isNotEmpty(roleMapper.selectUserByRoleId(role.getId()))){
                    throw new BaseException(BasicEnum.ROLE_ASSIGINED_USER);
                }
            }
            roleMapper.updateRole(role);
        }
    }
}
